golang踩坑之floa64精度丢失 |
您所在的位置:网站首页 › go float转string › golang踩坑之floa64精度丢失 |
问题:19.90转为float64类型,再乘以100,精度丢失
废话不说多,show you the code package main import ( "fmt" "strconv" ) func main() { num, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", 19.90), 64) fmt.Println(num) fmt.Println(num * 100) }运行输出 19.9 1989.999999999999819.9转成float64后,再乘以100,居然变成了1989.9999999999998 这个精度的问题要是出现在现金的问题上就厉害了! 解决使用包的decimal类型:github.com/shopspring/decimal 代码改为如下 package main import ( "fmt" "github.com/shopspring/decimal" "strconv" ) func main() { num, _ := strconv.ParseFloat(fmt.Sprintf("%.8f", 19.90), 64) fmt.Println(num) decimalValue := decimal.NewFromFloat(num) decimalValue = decimalValue.Mul(decimal.NewFromInt(100)) res,_ := decimalValue.Float64() fmt.Println(res) }运行输出 19.9 1990 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |